package com.ljx.config;

import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.orm.jpa.JpaProperties;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;

/**
 * @version V1.0
 * @author: Ljxpa
 * @date: 2020/04/20 17:13
 * @description:*/


@Configuration  //声明该类为配置类
@EnableTransactionManagement //开启spring的事务管理机制
@EnableJpaRepositories(
		basePackages = "com.ljx.dao",//dao层接口包名
		entityManagerFactoryRef = "primaryEntityManagerFactory"// 实体管理bean名称
)
public class RepositoryConfig {


 	@Primary //声明IOC中有多个相同对象时，优先注入本对象
	@Bean(name = "primaryJpaProperties")
	@ConfigurationProperties(prefix = "spring.jpa") //读取yml中的配置属性
	public JpaProperties jpaProperties() {
		return new JpaProperties();
	}

	//创建数据源
	@Bean(name = "primaryDataSource")
	@ConfigurationProperties(prefix = "spring.datasource")
	public DataSource druid() {
		return DataSourceBuilder.create().build();
	}

	//创建entityfactorybean，类似mybatis中的sessionfactorybean
	@Primary
	@Bean(name = "primaryEntityManagerFactory")
	public LocalContainerEntityManagerFactoryBean entityManagerFactory(@Qualifier("primaryDataSource") DataSource primaryDataSource,
																	   @Qualifier("primaryJpaProperties") JpaProperties jpaProperties,
																	   EntityManagerFactoryBuilder builder) {
		return builder
				// 设置数据源
				.dataSource(primaryDataSource)
				// 设置jpa配置
				.properties(jpaProperties.getProperties())
				// 设置实体包名
				.packages("com.ljx.entity")
				// 设置持久化单元名，用于@PersistenceContext注解获取EntityManager时指定数据源
				.persistenceUnit("primaryPersistenceUnit")
				.build();
	}

	//创建entityManager，类似mybatis中的sessionFactory
	@Bean(name = "primaryEntityManager")
	public EntityManager entityManager(@Qualifier("primaryEntityManagerFactory") EntityManagerFactory factory) {
		return factory.createEntityManager();
	}


}
